using System;
using System.Linq;
using System.ComponentModel;
using System.Windows.Data;
using Common;
using Common.Search;
using Microsoft.Practices.Prism.ViewModel;
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.Events;
using Microsoft.Practices.Prism.Regions;
using SearchModule.Events;
using SearchModule.Models;
using SearchModule.Services;

namespace SearchModule.ViewModels
{
    /// <summary>
    /// ViewModel for SearchInputViewModel.
    /// </summary>
    public class SearchResultsViewModel : NotificationObject, INavigationAware
    {
        private readonly IDataService _dataService;
        private readonly IEventAggregator _eventAggregator;
        private readonly IRegionManager _regionManager;
        private SearchResults _model;

        public SearchResultsViewModel(IDataService dataService, IEventAggregator eventAggregator, IRegionManager regionManager)
        {
            _dataService = dataService;
            _eventAggregator = eventAggregator;
            _regionManager = regionManager;

            // Get the data model from the data service.
            _model = _dataService.GetModel();
            DataItemsCV = new ListCollectionView(_model);

            _eventAggregator.GetEvent<SearchResultsUpdatedEvent>().Subscribe(SearchResultsUpdated, true);

            ItemClickCommand = new DelegateCommand<Uri>(OnItemClick);
        }

        public DelegateCommand<Uri> ItemClickCommand { get; private set; }

        private void OnItemClick(Uri itemURI)
        {
            this._regionManager.RequestNavigate(RegionNames.MainRegion, itemURI);
        }

        private void SearchResultsUpdated(string args)
        {
            // refresh the collection and raise property changed event
            _model = _dataService.GetModel();
            DataItemsCV = new ListCollectionView(_model);
            RaisePropertyChanged("DataItemsCV");
        }

        public ICollectionView DataItemsCV { get; private set; }

        #region INavigationAware Members
        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            // Called to see if this view can handle the navigation request.
            // If it can, this view is activated.
            return true;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
            // Called when this view is deactivated as a result of navigation to another view.
        }

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            // Called to initialize this view during navigation.
        }
        #endregion
    }
}
